<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Asymptix\HtmlDomParser\HtmlDomParser;
use Illuminate\Support\Facades\Log;
use App\Jobs\updateSectionsByUrlFromShuqiba;
use App\Models\Book;
use App\Models\Operation;
use GuzzleHttp\Client;

class updateBookSectionsFromShuqiba implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	private $url;
	private $book;
	
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct($url, Book $book) {
		$this->url = $url;
		$this->book = $book;
	}
	
	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		$book = $this->book;
		$html = new HtmlDomParser();
		$html->loadUrl($this->url);
		$sections = $html->find('.chapterlist', 1)->find('dd');
		$cSections = count($sections);
		if($book->thumbnail == 'nocover.jpg') {
			$img = $html->find('.book-img img', 0)->src;
			if(!strpos($img, 'nocover')) {
				$client = new Client();
				$nName = public_path('uploads/covers/'.$book->id.'-cover.jpg');
				$client->get($img, ['save_to' => $nName]);
				$book->thumbnail = $book->id . '-cover.jpg';
				$book->save();
			}
		}
		$abstract = $html->find('.book-intro', 0)->innertext();
		if(isset($abstract{strlen($book->abstract)})) {
			$book->abstract = $abstract;
			$book->save();
		}
		if($cSections > $book->sections->count() OR !$book->completed) {
			$i=0;
			$num = $book->completed ? $book->sections->count() : 0;
			foreach ($sections as $section) {
				$i++;
				if($i <= $num) continue;
				dispatch(new updateSectionsByUrlFromShuqiba($this->url.$section->find('a', 0)->href, $i, $cSections, $book));
			}
			Log::info($book->name.' => 加入队列完成，需更新： '.($i-$num).' 章');
			Operation::create([
				'action' => '小说更新-队列',
				'content' => $book->name.' => 加入队列完成，需更新： '.($i-$num).' 章',
			]);
		}else {
			Log::info($book->name.' => 无需更新');
			Operation::create([
				'action' => '小说更新-队列',
				'content' => $book->name.' => 无需更新'
			]);
		}
		return 0;
	}
}